<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Forpastime < forpastime@qq.com>
// +----------------------------------------------------------------------
namespace app\tenant\controller;

use app\tenant\model\UserModel;
use cmf\controller\AdminBaseController;
use think\Db;
use tree\Tree;
use app\admin\model\AdminMenuModel;
use think\facade\Cache;

class AdminUserController extends AdminBaseController
{
	
	 /**
     * 商户管理
     * @adminMenu(
     *     'name'   => '商户管理',
     *     'parent' => 'tenant/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户管理',
     *     'param'  => ''
     * )
     * @param userType 商户在系统中的角色  8
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $admin_id = cmf_get_current_admin_id();
        $user = Db::name("user")->where("id", $admin_id)->find();

        // if($user['tenant_id']!=0){//子商户账号权限不足！
        //         $this->error("权限不足！");
        // }
        $this->assign("is_admin", $user['tenant_id']==0?true:false);

        $userModel = new UserModel();

        /**搜索条件**/
        $userLogin = $this->request->param('user_login');
        $userEmail = trim($this->request->param('user_email'));

        $users = $userModel->getUsers($userLogin, $userEmail,$user['tenant_id']==0?$admin_id:$user['tenant_id']);

        // 获取分页显示
        $page = $users->render();

        $rolesSrc = Db::name('role')->select();
        $roles    = [];
        foreach ($rolesSrc as $r) {
            $roleId           = $r['id'];
            $roles["$roleId"] = $r;
        }
        $this->assign("page", $page);
        $this->assign("roles", $roles);
        $this->assign('users', $users);

        return $this->fetch();
    }

    public function login()
    {
        // $redirect = $this->request->param("redirect");
        // if (empty($redirect)) {
        //     $redirect = $this->request->server('HTTP_REFERER');
        // } else {
        //     if (strpos($redirect, '/') === 0 || strpos($redirect, 'http') === 0) {
        //     } else {
        //         $redirect = base64_decode($redirect);
        //     }
        // }
        // if(!empty($redirect)){
        //     session('login_http_referer', $redirect);
        // }
        // if (cmf_is_user_login()) { //已经登录时直接跳到首页
        //     return redirect($this->request->root() . '/');
        // } else {
            return $this->fetch("edit");
        // }
    }

    /**
     * 登录验证提交
     */
    public function doLogin()
    {
        if ($this->request->isPost()) {
            $validate = new \think\Validate([
                'captcha'  => 'require',
                'username' => 'require',
                'password' => 'require|min:6|max:32',
            ]);
            $validate->message([
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空',
                'password.max'     => '密码不能超过32个字符',
                'password.min'     => '密码不能小于6个字符',
                'captcha.require'  => '验证码不能为空',
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            if (!cmf_captcha_check($data['captcha'])) {
                $this->error(lang('CAPTCHA_NOT_RIGHT'));
            }

            $userModel         = new UserModel();
            $user['user_pass'] = $data['password'];
            if (Validate::is($data['username'], 'email')) {
                $user['user_email'] = $data['username'];
                $log                = $userModel->doEmail($user);
            } else if (cmf_check_mobile($data['username'])) {
                $user['mobile'] = $data['username'];
                $log            = $userModel->doMobile($user);
            } else {
                $user['user_login'] = $data['username'];
                $log                = $userModel->doName($user);
            }
            $session_login_http_referer = session('login_http_referer');
            $redirect                   = empty($session_login_http_referer) ? $this->request->root() : $session_login_http_referer;
            switch ($log) {
                case 0:
                    cmf_user_action('login');
                    $this->success(lang('LOGIN_SUCCESS'), $redirect);
                    break;
                case 1:
                    $this->error(lang('PASSWORD_NOT_RIGHT'));
                    break;
                case 2:
                    $this->error('账户不存在');
                    break;
                case 3:
                    $this->error('账号被禁止访问系统');
                    break;
                default :
                    $this->error('未受理的请求');
            }
        } else {
            $this->error("请求错误");
        }
    }

    /**
     * 商户管理
     * @adminMenu(
     *     'name'   => '添加管理员',
     *     'parent' => 'tenant/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '添加商户分管员',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function add()
    {
        $admin_id = cmf_get_current_admin_id();
        $user = Db::name("user")->where("id", $admin_id)->find();
        $this->assign('admin',$user);
        return $this->fetch();
    }

    /**
     * 商户添加提交
     * @adminMenu(
     *     'name'   => '商户添加提交',
     *     'parent' => 'add',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户添加提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        if ($this->request->isPost()) {
                if(!empty($_POST['role_id'])){
                    $this->error('商户用户不需要指定角色');
                }
                $admin_id = cmf_get_current_admin_id();
                $admin = DB::name('user')->where('id',$admin_id)->find();

                $result = $this->validate($this->request->param(), 'User');
                if ($result !== true) {
                    $this->error($result);
                } else {
                    $_POST['tenant_type'] = $_POST['tenant_type'];
                    $_POST['tenant_id'] = $admin['tenant_id']==0?$admin_id:$admin['tenant_id'];//新增商户的父级还是商户主管理员

                    $_POST['user_pass'] = cmf_password($_POST['user_pass']);
                    $result             = DB::name('user')->insertGetId($_POST);
                    if ($result !== false) {
                        $user = ['role_id'=>3,'user_id'=>$result];
                        $roleAdd =  DB::name('role_user')->insertGetId($user);
                        if($roleAdd){
                            $this->success("添加成功！", url("AdminUser/index"));
                        }else {
                            $this->error("添加失败！");
                        }
                    } else {
                        $this->error("添加失败！");
                    }
                }
            

        }
    }


    /**
     * 商户编辑
     * @adminMenu(
     *     'name'   => '商户分管员编辑',
     *     'parent' => 'tenant/AdminIndex/default',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户分管员编辑',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $content = hook_one('admin_user_edit_view');

        if (!empty($content)) {
            return $content;
        }

        $id    = $this->request->param('id', 0, 'intval');

        $user = DB::name('user')->where("id", $id)->find();
        $this->assign('user',$user);

        $admin_id = cmf_get_current_admin_id();
        $admin = Db::name("user")->where("id", $admin_id)->find();
        $this->assign('admin',$admin);
        return $this->fetch();
    }

       /**
     * 商户编辑提交
     * @adminMenu(
     *     'name'   => '商户编辑提交',
     *     'parent' => 'edit',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户编辑提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        if ($this->request->isPost()) {
            if (!empty($_POST['role_id']) && is_array($_POST['role_id'])) {
                $this->error("商户无需指定角色");

            }
                if (empty($_POST['user_pass'])) {
                    unset($_POST['user_pass']);
                } else {
                    $_POST['user_pass'] = cmf_password($_POST['user_pass']);
                }
                
                $result = $this->validate($this->request->param(), 'User.edit');

                if ($result !== true) {
                    // 验证失败 输出错误信息
                    $this->error($result);
                } else {
                    $result = DB::name('user')->update($_POST);
                    if ($result !== false) {
                        $uid = $this->request->param('id', 0, 'intval');
                        $this->success("保存成功！");
                    } else {
                        $this->error("保存失败！");
                    }
                }
        }
    }

    /**
     * 商户个人信息修改
     * @adminMenu(
     *     'name'   => '个人信息',
     *     'parent' => 'tenant/AdminIndex/default',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户个人信息修改',
     *     'param'  => ''
     * )
     */
    public function userInfo()
    {
        $id   = cmf_get_current_admin_id();
        $user = Db::name('user')->where("id", $id)->find();
        $this->assign($user);
        return $this->fetch();
    }

    /**
     * 商户个人信息修改提交
     * @adminMenu(
     *     'name'   => '商户个人信息修改提交',
     *     'parent' => 'userInfo',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户个人信息修改提交',
     *     'param'  => ''
     * )
     */
    public function userInfoPost()
    {
        if ($this->request->isPost()) {

            $data             = $this->request->post();
            $data['birthday'] = strtotime($data['birthday']);
            $data['id']       = cmf_get_current_admin_id();
            $create_result    = Db::name('user')->update($data);;
            if ($create_result !== false) {
                $this->success("保存成功！");
            } else {
                $this->error("保存失败！");
            }
        }
    }

    /**
     * 商户删除
     * @adminMenu(
     *     'name'   => '商户删除',
     *     'parent' => 'tenant/AdminIndex/default',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户删除',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id == 1) {
            $this->error("最高商户不能删除！");
        }
        $user = Db::name("user")->where("id", $id)->find();
        $admin_id = cmf_get_current_admin_id();

        // $admin = Db::name("user")->where("id", $admin_id)->find();

        if($admin_id!=1&&($user['tenant_type'] != 2 || $user['tenant_id']!=$admin_id)){//只能删除子商户账号
            $this->error("权限不足，删除失败！");

        }
        if (Db::name('user')->delete($id) !== false) {
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

    /**
     * 停用商户
     * @adminMenu(
     *     'name'   => '停用商户',
     *     'parent' => 'tenant/AdminIndex/default',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '停用商户',
     *     'param'  => ''
     * )
     */
    public function ban()
    {
        $id = $this->request->param('id', 0, 'intval');

        if (!empty($id)) {
            $user = Db::name("user")->where("id", $id)->find();
            $admin_id = cmf_get_current_admin_id();

            if($admin_id!=1&&($user['tenant_type'] != 2 || $user['tenant_id']!=$admin_id)){//只能删除子商户账号
                $this->error("权限不足，拉黑失败！");

            }

            $result = Db::name('user')->where(["id" => $id])->setField('user_status', '0');
            if ($result !== false) {
                $this->success("商户停用成功！", url("AdminUser/index"));
            } else {
                $this->error('商户停用失败！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }

    /**
     * 启用商户
     * @adminMenu(
     *     'name'   => '启用商户',
     *     'parent' => 'tenant/AdminIndex/default',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '启用商户',
     *     'param'  => ''
     * )
     */
    public function cancelBan()
    {
        $id = $this->request->param('id', 0, 'intval');
        
        if (!empty($id)) {
            $user = Db::name("user")->where("id", $id)->find();
            $admin_id = cmf_get_current_admin_id();

            if($user['tenant_type'] != 2 || $user['tenant_id']!=$admin_id){//只能删除子商户账号
                $this->error("权限不足，拉黑失败！");

            }

            $result = Db::name('user')->where(["id" => $id])->setField('user_status', '1');
            if ($result !== false) {
                $this->success("商户启用成功！", url("AdminUser/index"));
            } else {
                $this->error('商户启用失败！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }

    /**
     * 分管员权限管理
     * 从商户的权限中选择添加权限给商户管理员
     * @adminMenu(
     *     'name'   => '商户管理员权限管理',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '分管员权限管理',
     *     'param'  => ''
     * )
     */
    public function authorize()
    {
        $id = $this->request->param('id', 0, 'intval');
        $admin_id = cmf_get_current_admin_id();

        if (!empty($id)) {
            $user = Db::name("user")->where("id", $id)->find();
            if(($user['tenant_type'] != 2 || $user['tenant_id']!=$admin_id) && $admin_id !=1){//只能删除子商户账号
                $this->error("权限不足，无法给该用户授权！");
            }
        } else {
            $this->error('数据传入失败！');
        }

        $content = hook_one('admin_rbac_authorize_view');

        if (!empty($content)) {
            return $content;
        }
        $AuthAccess     = Db::name("AuthAccess");
        $adminMenuModel = new AdminMenuModel();
        //角色ID
        $roleId =  Db::name("roleUser")->where("user_id", $user['tenant_id'])->value('role_id');

        $tree       = new Tree();
        $tree->icon = ['│ ', '├─ ', '└─ '];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        $result = $adminMenuModel->menuCache();

        $newMenus      = [];
        $privilegeData = $AuthAccess->where("role_id", $roleId)->column("rule_name");//获取权限表数据

        $tenantAuthAccess =Db::name('tenantAuthAccess')->where("user_id", $id)->column("rule_name");

        foreach ($result as $m) {
            $newMenus[$m['id']] = $m;
            
        }

        foreach ($result as $n => $t) {
            if($this->_isChecked($t, $privilegeData)){//先判断商户权限对应的权限
                if(!empty($tenantAuthAccess)){
                    
                    $result[$n]['checked']      = $this->_isChecked($t, $tenantAuthAccess)?'checked':'';
                    
                }else{
                    $result[$n]['checked']      = '';
                }
                
                $result[$n]['level']        = $this->_getLevel($t['id'], $newMenus);
                $result[$n]['style']        = empty($t['parent_id']) ? '' : 'display:none;';
                $result[$n]['parentIdNode'] = ($t['parent_id']) ? ' class="child-of-node-' . $t['parent_id'] . '"' : '';
            }else{
                unset($result[$n]);
            }
            
        }


        $str = "<tr id='node-\$id'\$parentIdNode  style='\$style'>
                   <td style='padding-left:30px;'>\$spacer<input type='checkbox' name='menuId[]' value='\$id' level='\$level' \$checked onclick='javascript:checknode(this);'> \$name</td>
    			</tr>";
        $tree->init($result);

        $category = $tree->getTree(0, $str);

        $this->assign("userId", $id);

        $this->assign("category", $category);
        $this->assign("roleId", $roleId);
        return $this->fetch();
    }

    /**
     * 商户管理员授权提交
     * @adminMenu(
     *     'name'   => '商户管理员授权提交',
     *     'parent' => 'authorize',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '商户管理员授权提交',
     *     'param'  => ''
     * )
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function authorizePost()
    {
        if ($this->request->isPost()) {
            $roleId = $this->request->param("roleId", 0, 'intval');
            $userId = $this->request->param("userId", 0, 'intval');

            if (!$userId) {
                $this->error("需要授权的用户不存在！");
            }
            if (is_array($this->request->param('menuId/a')) && count($this->request->param('menuId/a')) > 0) {

                Db::name("tenantAuthAccess")->where(["user_id" => $userId, 'type' => 'admin_url'])->delete();
                foreach ($_POST['menuId'] as $menuId) {
                    $menu = Db::name("adminMenu")->where("id", $menuId)->field("app,controller,action")->find();
                    if ($menu) {
                        $app    = $menu['app'];
                        $model  = $menu['controller'];
                        $action = $menu['action'];
                        $name   = strtolower("$app/$model/$action");
                        Db::name("tenantAuthAccess")->insert(["role_id" => $roleId, "rule_name" => $name, 'type' => 'admin_url','user_id'=>$userId]);
                    }
                }

                Cache::clear('admin_tenant_menus');// 删除后台菜单缓存

                $this->success("授权成功！");
            } else {
                //当没有数据时，清除当前角色授权
                Db::name("tenantAuthAccess")->where("user_id", $userId)->delete();
                $this->error("没有接收到数据，执行清除授权成功！");
            }
        }
    }

    /**
     * 检查指定菜单是否有权限
     * @param array $menu menu表中数组
     * @param       $privData
     * @return bool
     */
    private function _isChecked($menu, $privData)
    {
        $app    = $menu['app'];
        $model  = $menu['controller'];
        $action = $menu['action'];
        $name   = strtolower("$app/$model/$action");
        if ($privData) {
            if (in_array($name, $privData)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }

    /**
     * 获取菜单深度
     * @param       $id
     * @param array $array
     * @param int   $i
     * @return int
     */
    protected function _getLevel($id, $array = [], $i = 0)
    {
        if ($array[$id]['parent_id'] == 0 || empty($array[$array[$id]['parent_id']]) || $array[$id]['parent_id'] == $id) {
            return $i;
        } else {
            $i++;
            return $this->_getLevel($array[$id]['parent_id'], $array, $i);
        }
    }
}